import * as vscode from 'vscode';
import { LanguageClient, LanguageClientOptions, ServerOptions, TransportKind } from 'vscode-languageclient/node';

let client: LanguageClient;

export function activate(context: vscode.ExtensionContext) {
    console.log('墨言语言支持插件已激活');

    // 配置语言服务器
    const serverModule = context.asAbsolutePath('out/server/server.js');
    const serverOptions: ServerOptions = {
        run: { module: serverModule, transport: TransportKind.ipc },
        debug: { module: serverModule, transport: TransportKind.ipc }
    };

    const clientOptions: LanguageClientOptions = {
        documentSelector: [
            { scheme: 'file', language: 'moyan' },
            { scheme: 'untitled', language: 'moyan' }
        ],
        synchronize: {
            fileEvents: vscode.workspace.createFileSystemWatcher('**/.墨言')
        }
    };

    // 创建语言客户端
    client = new LanguageClient('moyanLanguageServer', '墨言语言服务器', serverOptions, clientOptions);
    
    // 启动语言客户端
    client.start();

    // 注册格式化命令
    const formatCommand = vscode.commands.registerCommand('moyan.formatDocument', async () => {
        const editor = vscode.window.activeTextEditor;
        if (!editor) {
            vscode.window.showErrorMessage('没有活动的编辑器');
            return;
        }

        if (editor.document.languageId !== 'moyan') {
            vscode.window.showErrorMessage('当前文档不是墨言语言文件');
            return;
        }

        await vscode.commands.executeCommand('editor.action.formatDocument');
    });

    // 注册语法检查命令
    const diagnosticsCommand = vscode.commands.registerCommand('moyan.runDiagnostics', async () => {
        const editor = vscode.window.activeTextEditor;
        if (!editor) {
            vscode.window.showErrorMessage('没有活动的编辑器');
            return;
        }

        if (editor.document.languageId !== 'moyan') {
            vscode.window.showErrorMessage('当前文档不是墨言语言文件');
            return;
        }

        // 触发语法检查
        await client.sendRequest('workspace/executeCommand', {
            command: 'moyan.runDiagnostics',
            arguments: [editor.document.uri.toString()]
        });

        vscode.window.showInformationMessage('语法检查已完成');
    });

    context.subscriptions.push(formatCommand);
    context.subscriptions.push(diagnosticsCommand);
    context.subscriptions.push(client);

    // 状态栏项目
    const statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100);
    statusBarItem.text = "$(file-code) 墨言";
    statusBarItem.tooltip = "墨言语言模式";
    statusBarItem.show();
    context.subscriptions.push(statusBarItem);

    console.log('墨言语言支持插件加载完成');
}

export function deactivate(): Thenable<void> | undefined {
    if (!client) {
        return undefined;
    }
    return client.stop();
}